﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Text.RegularExpressions;

namespace SiteParser.Core.Formatters
{
	public class HtmlTagFormatter : IFormatter
	{
		protected const string NEW_LINE_HTML_REGEX_PATTERN = @"<\s*br\s*/\s*>";
		protected const string TAG_REGEX_PATTERN = @"<[^>]+>";
		protected const string NEW_LINE_FORMATTED_VALUE = "\n";

		protected readonly Regex newLineHtmlRegex;
		protected readonly Regex tagRegex;

		public HtmlTagFormatter()
		{
			newLineHtmlRegex = new Regex(NEW_LINE_HTML_REGEX_PATTERN, RegexOptions.Compiled);
			tagRegex = new Regex(TAG_REGEX_PATTERN, RegexOptions.Compiled);
		}

		#region IFormatter Members

		public string Format(string stringToFormat) {
			string result = HttpUtility.HtmlDecode(stringToFormat);
			//replace all "<br/>" to new lines
			result = !string.IsNullOrEmpty(result) ? newLineHtmlRegex.Replace(result, NEW_LINE_FORMATTED_VALUE) : string.Empty;
			//remove all tags
			result = !string.IsNullOrEmpty(result) ? tagRegex.Replace(result, string.Empty) : string.Empty;

			return result;
		}

		#endregion
	}
}
